/*
 * @lc app=leetcode.cn id=75 lang=javascript
 *
 * [75] 颜色分类
 */

// @lc code=start
/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var sortColors = function(nums) {
  if(!nums) return;
  let l = 0, r = nums.length-1, k = 0;
  while(k <= r){
    if(nums[k] == 0){
      [nums[l++], nums[k]] = [nums[k], nums[l]];
      k++;
    } else if(nums[k] == 2){
      [nums[r--], nums[k]] = [nums[k], nums[r]];
    } else {
      k++;
    }
  }
  return nums;
};

/**
 * 复习 2021-08-04
 */
var swper = function(arr, a, b){
  [arr[a], arr[b]] = [arr[b], arr[a]];
}
var sortColors = function(nums) {
  if(!nums.length) return nums;
  let red = 0, blue = nums.length - 1;
  for (let i = 0; i <= blue;) {
    switch(nums[i]){
      case 0: 
        swper(nums, red, i);
        red++;
        i++;
        break;
      case 2: 
        swper(nums, blue, i);
        blue--;
        break;
      default: 
        i++;
    }
  }
  return nums;
}
// @lc code=end

